<?php


namespace App\Admin\Forms\Config;


use App\Models\Config\SystemData;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Arr;

class ProtocolConfig extends Form
{
    public static function label() :array
    {
        return [
            SystemData::DATA_PROTOCOL_SERVICE =>"服务协议",
            SystemData::DATA_PROTOCOL_REGISTER =>"注册协议",
        ];
    }



    public function form()
    {
        $label = static::label();

        $this->editor(SystemData::DATA_PROTOCOL_SERVICE,Arr::get($label,SystemData::DATA_PROTOCOL_SERVICE));
        $this->editor(SystemData::DATA_PROTOCOL_REGISTER,Arr::get($label,SystemData::DATA_PROTOCOL_REGISTER));
    }


    /**
     * 处理表单的提交
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $fields = static::label();
        foreach ($fields as $key => $value){
            SystemData::updateOrCreate(["key"=>$key],["name" => $value, "value" => Arr::get($input,$key)]);
        }
        return $this->response()->success('设置成功');
    }

    /**
     * 表单默认值
     * @return mixed
     */
    public function default()
    {
        $keys = static::label();
        $all = SystemData::whereIn("key",array_keys($keys))->pluck("value","key");
        $values = [];
        foreach ($keys as $key => $v){
            $values[$key] = Arr::get($all,$key);
        }
        return $values;
    }


    public function savedScript()
    {
        return <<<'JS'
    if (data.status) {
        setTimeout(function () {
          location.reload()
        }, 1200);
    }
JS;
    }


}
